import axios from 'axios'
import apiList from './serviceConfig'
import config from './config'
import _ from 'lodash'

axios.defaults.withCredentials = true

const servicePlugin = {};

servicePlugin.install = function(Vue, options) {
    Vue.prototype.$$http = function(name, str, data) {
        let regExp = /\{ *([\w_\-]+) *\}/g,
            url = apiList[name].url;

        if (Array.isArray(str)) {
            let replaceList = url.match(regExp);
            _.forEach(replaceList, (item, index) => {
                if (str[index] == undefined || str[index] == null)
                    url = url.replace(item, '')
                else
                    url = url.replace(item, str[index])
            })
        } else {
            url = url.replace(regExp, str);
        }

        // 添加时间戳
        if(url && url.indexOf("door") > -1 && name !== 'USER_LOGIN') {
            var time = new Date().getTime()
            if(url.indexOf("?") > -1) {
                url += "&_=" + time
            } else {
                url += "?_=" + time
            }
        }

        return axios({
            method: apiList[name].method,
            url: url,
            data: data
        }).then(res => {
            if(res.data === 'logout' && name !== 'GET_CURRENT_USER') {
                // session过期了，强制退出
                config.router.push("/login")
                config.app.$message.info("已退出，请重新登录")
            }
            return res.data
        }).catch(err => {
            console.log(err);
            config.app.$message.error("程序或网络错误！")
        })
    }
}

export default servicePlugin;